package com.falcon.service.impl;

import com.falcon.config.GeneratorConfig;
import com.falcon.scanner.IVueComponentScanner;
import com.falcon.service.IGenMenuComponentService;
import com.falcon.utils.PathUtil;
import com.falcon.domain.po.MenuComponentPO;
import com.falcon.domain.req.MenuComponentQuery;
import com.falcon.mapper.IMenuComponentMapper;
import com.swan.core.utils.ListUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zongf
 * @date 2024-03-14
 **/
@Slf4j
@Service
public class GenMenuComponentService implements IGenMenuComponentService {

    @Autowired
    private IMenuComponentMapper menuComponentMapper;

    @Autowired
    private IVueComponentScanner menuComponentScanner;

    @Autowired
    protected GeneratorConfig generatorConfig;

    private List<MenuComponentPO> getScanComponents() {
        GeneratorConfig.VbenConfig vbenConfig = generatorConfig.getVbenConfig();

        String dirPath =  PathUtil.getPath(generatorConfig.getProjectPath(), vbenConfig.getRelativeBasePath(), vbenConfig.getPagesPath(), "","");
        List<MenuComponentPO> scanComponents = menuComponentScanner.doScan(dirPath);
        return scanComponents;
    }

    @Override
    public List<MenuComponentPO> queryNewComponents(MenuComponentQuery query) {

        // 查询数据库中所有组件
        List<MenuComponentPO> dbComponents = this.menuComponentMapper.selectList(null);

        // 扫描项目中所有组件
        Map<String, MenuComponentPO> srcMapPo = ListUtil.toMap(dbComponents, MenuComponentPO::getSrcPath);

        // 过滤获取待导入的
        List<MenuComponentPO> scanComponents = getScanComponents();

        List<MenuComponentPO> candidates = scanComponents.stream()
                .filter(existTable -> !srcMapPo.containsKey(existTable.getSrcPath()))
                .sorted(Comparator.comparing(MenuComponentPO::getSrcPath))
                .collect(Collectors.toList());

        return candidates;
    }

    @Override
    public void imports(List<String> srcPaths) {
        // 扫描项目中所有组件
        List<MenuComponentPO> scanComponents = getScanComponents();

        Map<String, MenuComponentPO> srcMapPo = ListUtil.toMap(scanComponents, MenuComponentPO::getSrcPath);

        List<MenuComponentPO> importPos = srcPaths.stream().map(srcMapPo::get).collect(Collectors.toList());

        importPos.forEach(this.menuComponentMapper::insertNotNull);
    }
}
